package models

import (
	"time"
)

type Graduation struct {
	Id        int       `xorm:"not null pk autoincr comment('自增ID') INT(11)"`
	StudentId int       `xorm:"not null comment('学员编号') unique INT(11)"`
	SchoolId  int       `xorm:"not null comment('发证培训机构编号') index INT(11)"`
	GrantDate time.Time `xorm:"not null comment('结业证书发放日期') DATE"`
	PdfId     int       `xorm:"not null comment('结业证书PDF文件ID') INT(11)"`
	PdfUrl    string    `xorm:"comment('电子证书文件路径') VARCHAR(255)"`
}

type PrintGraduation struct {
	Institution_code  string
	Student_name      string
	Sex               string
	Sign_in_time      time.Time
	Grant_date        time.Time
	Training_car_type string
	School_name       string
	Date_time         time.Time
}

func (m *Graduation) AddGraduation() (int64, error) {
	return engine.Insert(m)
}

func (c *Graduation) GetStudentGraduationDate(student_id int64) (list Graduation, err error) {
	_, err = engine.Table("dts_graduation").
		Where("student_id = ?", student_id).
		Get(&list)
	return list, err
}

func (c *Graduation) GetPrintGraduation(id string) (list PrintGraduation, err error) {
	_, err = engine.Table("dts_graduation").Alias("gn").
		Select("st.institution_code,ur.name as student_name,ur.sex,st.sign_in_time,gn.grant_date,st.training_car_type,sl.name as school_name").
		Join("left", []string{"dts_student", "st"}, "gn.student_id = st.id").
		Join("left", []string{"dts_user", "ur"}, "st.user_id = ur.id").
		Join("left", []string{"dts_school", "sl"}, "gn.school_id = sl.id").
		Where("gn.id = ?", id).
		Get(&list)
	return list, err
}

func (c *Graduation) Save() *Graduation {
	engine.Insert(c)
	return c
}

func (c *Graduation) Edit(fields ...string) bool {
	var (
		err error
	)
	_, err = engine.Id(c.Id).Cols(fields...).Update(c)
	if err != nil {
		return false
	}
	return true
}

func (c *Graduation) GetGraduationByStudedntId(id int64) (has bool, list Graduation, err error) {
	has, err = engine.Table("dts_graduation").
		Where("student_id = ?", id).
		Get(&list)
	return has, list, err
}

func (c *Graduation) Remove(student_id string) (err error) {
	if _, err = engine.Exec("delete from dts_graduation where student_id = ? limit 1", student_id); err != nil {
		return err
	}
	return nil
}
